package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class PgStatActivityUtil {

    public static List<Integer> getClusterConnectionSize(List<String> hosts, String user, String password,
                                                         String clientHost, String driver, String database) {
        List<Integer> connectionSizes = new ArrayList<>();
        for (String host : hosts) {
            String url = "jdbc:" + driver + "://" + host + "/" + database + "?loggerLevel=OFF";
            int connectionSize = getConnectionSize(url, user, password, clientHost);
            if (connectionSize == 0) {
                connectionSizes.add(0);
            } else {
                connectionSizes.add(connectionSize - 1);
            }
        }
        return connectionSizes;
    }

    private static int getConnectionSize(String url, String user, String password, String clientHost) {
        try (Connection connection = DriverManager.getConnection(url, user, password);
             Statement statement = connection.createStatement();) {
            ResultSet resultSet = statement.executeQuery("select count(*) from pg_stat_activity where client_addr = " +
                "'" + clientHost + "' and application_name = 'PostgreSQL JDBC Driver';");
            if (resultSet.next()) {
                return resultSet.getInt(1);
            }
        } catch (SQLException e) {
            return 0;
        }
        return 0;
    }

    public static void main(String[] args) {
        List<String> hosts = new ArrayList<>();
        hosts.add("192.168.0.243:14100");
        hosts.add("192.168.0.243:14200");
        hosts.add("192.168.0.243:14300");
        System.out.println(getClusterConnectionSize(hosts, "test", "huawei123.", "192.168.0.28", "opengauss", "test"));
//        System.out.println(getConnectionSize("jdbc:opengauss://192.168.0.243:14100/test", "test", "huawei123.", "192.168.0.28"));
    }
}
